package Java7_Concurrency_Cookbook.concurrency_test.reentrant_lock_test;

import java.util.Collection;
import java.util.concurrent.TimeUnit;

/**
 * ReentrantLock.getOwner(): 只有一个线程能够执行Lock对象保护的临界区, getOwner()返回这个线程的名称<br/>
 * ReentrantLock.getQueuedThreads(): 等待执行临界区代码的线程列表<br/>
 * ReentrantLock.hasQueuedThreads(): 是否有线程正在等待获取锁<br/>
 * ReentrantLock.getQueueLength(): 正在等待锁的线程数<br/>
 * ReentrantLock.isLocked(): 这个锁是否被一个线程战友<br/>
 * ReentrantLock.isFair(): 表明该锁是否为公平模式<br/>
 * ReentrantLock.getHoldCount(): 返回当前线程获取到锁的次数<br/>
 * ReentrantLock.isHeldByCurrentThread(): 当前线程是否持有此锁<br/>
 * @author lixiangke
 * @date 2017/12/4
 */
public class Main {
    public static void main(String[] args) throws InterruptedException {
        MyLock lock = new MyLock();
        Thread[] threads = new Thread[5];
        for (int i = 0; i < 5; i++) {
            Task task = new Task(lock);
            threads[i] = new Thread(task);
            threads[i].start();
        }

        for (int i = 0; i < 15; i++) {
            System.out.printf("Main: Logging the lock\n");
            System.out.printf("**********************\n");
            System.out.printf("Lock: Owner: %s\n", lock.getOwnerName());
            System.out.printf("Lock: Queued Threads: %s\n", lock.hasQueuedThreads());
            if (lock.hasQueuedThreads()) {
                System.out.printf("Lock: Queue Length: %d\n", lock.getQueueLength());
                System.out.printf("Lock: Queue Threads: ");
                Collection<Thread> lockedThreads = lock.getThreads();
                for (Thread lockedThread : lockedThreads) {
                    System.out.printf("%s ", lockedThread.getName());
                }
                System.out.printf("\n");
            }
            System.out.printf("Lock: Fairness: %s\n", lock.isFair());
            System.out.printf("Lock: Locked: %s\n", lock.isLocked());
            System.out.printf("**********************\n");
            TimeUnit.SECONDS.sleep(1);
        }

    }
}
